package com.pdlocation.util;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 电池优化设置跳转工具类
 * 处理不同厂商系统的电池优化设置页面跳转
 */
public class BatteryOptimizationUtils {
    private static final String TAG = "BatteryOptimizationUtils";
    private static final String HUAWEI_PACKAGE = "com.huawei.systemmanager";
    private static final String XIAOMI_PACKAGE = "com.miui.securitycenter";
    private static final String OPPO_PACKAGE = "com.oppo.safe";
    private static final String VIVO_PACKAGE = "com.vivo.permissionmanager";
    private static final String MEIZU_PACKAGE = "com.meizu.safe";
    private static final String SAMSUNG_PACKAGE = "com.samsung.android.lool";
    private static final String LETV_PACKAGE = "com.letv.android.letvsafe";

    /**
     * 检查是否已开启电池优化白名单
     */
    public static boolean isIgnoringBatteryOptimizations(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            Log.d(TAG, "Device API < 23, battery optimization not required");
            return true;
        }

        AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        String opStr;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 使用 RUN_ANY_IN_BACKGROUND
            opStr = getOpStrValue("OPSTR_RUN_ANY_IN_BACKGROUND");
            Log.d(TAG, "Checking battery optimization with OPSTR_RUN_ANY_IN_BACKGROUND");
        } else {
            // Android 6.0-9.0 使用 IGNORE_BATTERY_OPTIMIZATIONS
            opStr = getOpStrValue("OPSTR_IGNORE_BATTERY_OPTIMIZATIONS");
            Log.d(TAG, "Checking battery optimization with OPSTR_IGNORE_BATTERY_OPTIMIZATIONS");
        }

        if (opStr == null) {
            Log.e(TAG, "Failed to get OPSTR value for current SDK version");
            return false;
        }

        try {
            ApplicationInfo appInfo = context.getApplicationInfo();
            String packageName = context.getPackageName();
            int mode;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10+ 使用 unsafeCheckOpNoThrow
                Method method = AppOpsManager.class.getMethod("unsafeCheckOpNoThrow",
                        String.class, int.class, String.class);
                mode = (int) method.invoke(appOps, opStr, appInfo.uid, packageName);
                Log.d(TAG, "Checked battery optimization mode (API 29+): " + mode);
            } else {
                // Android 6.0-9.0 使用 checkOpNoThrow
                Method method = AppOpsManager.class.getMethod("checkOpNoThrow",
                        String.class, int.class, String.class);
                mode = (int) method.invoke(appOps, opStr, appInfo.uid, packageName);
                Log.d(TAG, "Checked battery optimization mode (API 23-28): " + mode);
            }

            boolean result = mode == AppOpsManager.MODE_ALLOWED;
            Log.d(TAG, "Battery optimization ignored: " + result);
            return result;
        } catch (Exception e) {
            Log.e(TAG, "Check battery optimization status failed", e);
            return false;
        }
    }

    /**
     * 通过反射获取AppOpsManager中的OPSTR常量值
     */
    private static String getOpStrValue(String fieldName) {
        try {
            Field field = AppOpsManager.class.getDeclaredField(fieldName);
            String value = (String) field.get(null);
            Log.d(TAG, "Got OPSTR value: " + fieldName + " = " + value);
            return value;
        } catch (NoSuchFieldException e) {
            // 处理常量不存在的情况
            Log.w(TAG, "Field not found: " + fieldName + ", trying alternative approach");

            // 尝试直接返回字符串值
            if ("OPSTR_IGNORE_BATTERY_OPTIMIZATIONS".equals(fieldName)) {
                return "android:ignore_battery_optimizations";
            } else if ("OPSTR_RUN_ANY_IN_BACKGROUND".equals(fieldName)) {
                return "android:run_any_in_background";
            }

            return null;
        } catch (Exception e) {
            Log.e(TAG, "Failed to get OPSTR value: " + fieldName, e);
            return null;
        }
    }

    /**
     * 显示电池优化设置对话框并跳转
     */
    public static void showBatteryOptimizationDialog(final Activity activity, final int requestCode) {

        if (activity == null || activity.isFinishing()) {
            Log.e(TAG, "Activity is null or finishing, cannot show dialog");
            return;
        }

        // 先检查是否需要优化
        if (isIgnoringBatteryOptimizations(activity)) {
            Log.d(TAG, "Battery optimization already ignored, no need to show dialog");
            return;
        }

        new AlertDialog.Builder(activity)
                .setTitle("电池优化设置")
                .setMessage("为确保应用在后台正常运行，请关闭电池优化。")
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        goToBatterySettings(activity, requestCode);
                    }
                })
                .setNegativeButton("取消", null)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        Log.d(TAG, "Battery optimization dialog dismissed");
                    }
                })
                .show();
    }

    /**
     * 跳转至电池优化设置页面
     *
     * @param activity    宿主Activity
     * @param requestCode 请求码，用于onActivityResult回调
     * @return 是否成功启动跳转
     */
    public static boolean goToBatterySettings(Activity activity, int requestCode) {
        if (activity == null || activity.isFinishing()) {
            Log.e(TAG, "Activity is null or finishing, cannot start intent");
            return false;
        }

        Log.d(TAG, "Trying to go to battery settings, API: " + Build.VERSION.SDK_INT);

        // 先尝试原生设置页面
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + activity.getPackageName()));

                if (isIntentAvailable(activity, intent)) {
                    Log.d(TAG, "Starting native battery optimization settings");
                    activity.startActivityForResult(intent, requestCode);
                    return true;
                } else {
                    Log.w(TAG, "Native battery optimization settings not available");
                }
            } catch (Exception e) {
                Log.e(TAG, "Failed to start native battery optimization settings", e);
            }
        }

        // 尝试厂商特定设置页面
        String brand = Build.BRAND.toLowerCase();
        Log.d(TAG, "Device brand: " + brand);

        try {
            Intent intent;

            if (brand.contains("huawei") || brand.contains("honor")) {
                // 华为/荣耀
                intent = new Intent();
                intent.setComponent(new ComponentName(HUAWEI_PACKAGE,
                        "com.huawei.systemmanager.optimize.process.ProtectActivity"));
                Log.d(TAG, "Trying Huawei battery settings");
            } else if (brand.contains("xiaomi") || brand.contains("mi")) {
                // 小米
                intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                intent.setClassName(XIAOMI_PACKAGE,
                        "com.miui.securitycenter.permission.PermissionEditorActivity");
                intent.putExtra("extra_pkgname", activity.getPackageName());
                Log.d(TAG, "Trying Xiaomi battery settings");
            } else if (brand.contains("oppo")) {
                // OPPO
                intent = new Intent();
                intent.setComponent(new ComponentName(OPPO_PACKAGE,
                        "com.oppo.safe.permission.startup.StartupAppListActivity"));
                Log.d(TAG, "Trying OPPO battery settings");
            } else if (brand.contains("vivo") || brand.contains("bbk")) {
                // VIVO
                intent = new Intent();
                intent.setComponent(new ComponentName(VIVO_PACKAGE,
                        "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
                Log.d(TAG, "Trying VIVO battery settings");
            } else if (brand.contains("meizu")) {
                // 魅族
                intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
                intent.putExtra("packageName", activity.getPackageName());
                intent.setClassName(MEIZU_PACKAGE,
                        "com.meizu.safe.security.AppSecActivity");
                Log.d(TAG, "Trying Meizu battery settings");
            } else if (brand.contains("samsung")) {
                // 三星
                intent = new Intent();
                intent.setComponent(new ComponentName(SAMSUNG_PACKAGE,
                        "com.samsung.android.lool.battery.BatteryActivity"));
                intent.putExtra("appPackage", activity.getPackageName());
                intent.putExtra("appTitle", getApplicationName(activity));
                Log.d(TAG, "Trying Samsung battery settings");
            } else if (brand.contains("letv") || brand.contains("leeco")) {
                // 乐视
                intent = new Intent();
                intent.setComponent(new ComponentName(LETV_PACKAGE,
                        "com.letv.android.letvsafe.AutobootManageActivity"));
                intent.putExtra("packageName", activity.getPackageName());
                Log.d(TAG, "Trying Letv battery settings");
            } else {
                // 其他品牌，尝试跳转到应用详情页
                intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + activity.getPackageName()));
                Log.d(TAG, "Trying generic app details page");
            }

            if (isIntentAvailable(activity, intent)) {
                Log.d(TAG, "Starting manufacturer-specific battery settings");
                activity.startActivityForResult(intent, requestCode);
                return true;
            } else {
                Log.w(TAG, "Manufacturer-specific battery settings not available");
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to start manufacturer-specific battery settings", e);
        }

        // 所有方式失败时，尝试应用详情页
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));

            if (isIntentAvailable(activity, intent)) {
                Log.d(TAG, "Starting generic app details page as fallback");
                activity.startActivityForResult(intent, requestCode);
                return true;
            } else {
                Log.e(TAG, "Generic app details page not available either");
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to start generic app details page", e);
        }

        // 显示失败提示
        if (!activity.isFinishing()) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, "无法自动跳转电池优化设置，请手动设置",
                            Toast.LENGTH_LONG).show();
                }
            });
        }

        return false;
    }

    /**
     * 安全启动Intent（处理ActivityNotFoundException）
     */
    private static boolean startIntentSafely(Activity activity, Intent intent, int requestCode) {
        if (activity == null || activity.isFinishing()) {
            Log.e(TAG, "Activity is null or finishing, cannot start intent safely");
            return false;
        }

        try {
            Log.d(TAG, "Starting intent safely: " + intent.toString());
            activity.startActivityForResult(intent, requestCode);
            return true;
        } catch (ActivityNotFoundException e) {
            Log.e(TAG, "Activity not found: " + intent.toString(), e);
            return false;
        } catch (Exception e) {
            Log.e(TAG, "Start activity failed", e);
            return false;
        }
    }

    /**
     * 检查Intent是否可处理
     */
    private static boolean isIntentAvailable(Context context, Intent intent) {
        if (context == null || intent == null) {
            Log.w(TAG, "Context or Intent is null, returning false for intent availability");
            return false;
        }

        try {
            PackageManager pm = context.getPackageManager();
            List<ResolveInfo> list = pm.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            boolean result = list != null && list.size() > 0;
            Log.d(TAG, "Intent availability: " + intent.toString() + " = " + result);
            return result;
        } catch (Exception e) {
            Log.e(TAG, "Error checking intent availability", e);
            return false;
        }
    }

    /**
     * 兼容旧版MIUI系统的特殊处理
     */
    public static void handleLegacyXiaomi(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ||
                !Build.BRAND.toLowerCase().contains("xiaomi")) {
            Log.d(TAG, "Not a legacy Xiaomi device, skipping special handling");
            return;
        }

        try {
            String packageName = context.getPackageName();
            AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            Class<?> appOpsClass = Class.forName(appOps.getClass().getName());
            Method checkOp = appOpsClass.getMethod("checkOp", String.class, int.class, String.class);

            // 旧版MIUI使用反射获取OP值
            int opValue = 43; // OP_IGNORE_BATTERY_OPTIMIZATIONS的常量值

            int mode = (Integer) checkOp.invoke(appOps,
                    "android:ignore_battery_optimizations",
                    android.os.Process.myUid(),
                    packageName);

            if (mode != AppOpsManager.MODE_ALLOWED) {
                Log.d(TAG, "Legacy Xiaomi device needs special permission handling");
                // 旧版MIUI需要申请特殊权限
                if (context instanceof Activity) {
                    Activity activity = (Activity) context;
                    Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                    intent.setClassName(XIAOMI_PACKAGE,
                            "com.miui.securitycenter.permission.PermissionEditorActivity");
                    intent.putExtra("extra_pkgname", packageName);

                    if (isIntentAvailable(activity, intent)) {
                        startIntentSafely(activity, intent, 1001);
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Legacy Xiaomi handling failed", e);
        }
    }

    private static String getApplicationName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo applicationInfo = null;

        try {
            applicationInfo = packageManager.getApplicationInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return (String) (applicationInfo != null
                ? packageManager.getApplicationLabel(applicationInfo)
                : "Unknown");
    }
}